package com.leyou.auth.controller;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: taft
 * @Date: 2018-10-25 11:40
 */
@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AuthService authService;

    /***
     *认证的研发，那么收到的参数只能是用户名和密码
     */
    @PostMapping("accredit")
    public ResponseEntity<Void> accredit(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response){
        //把用户名和密码交给服务对象，由服务对象完成认证
        String token = authService.accredit(username,password,jwtProperties);

        if (StringUtils.isNotBlank(token)){
            //不为空要把结果写入到cookie中

            CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),token,jwtProperties.getCookieMaxAge());

            //201
            return ResponseEntity.status(HttpStatus.CREATED).build();
        }

        //401
        return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}

    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(
            @CookieValue("LY_TOKEN")String token,
            HttpServletRequest request,
            HttpServletResponse response){

        UserInfo userInfo = this.authService.verify(token,jwtProperties);

        if (null!=userInfo){


            //重新生成一次token
            try {
                String reToken = JwtUtils.generateToken(userInfo,jwtProperties.getPrivateKey(),jwtProperties.getExpire());

                //并且把token存在cookie中
                CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),reToken,jwtProperties.getCookieMaxAge());
            } catch (Exception e) {
                e.printStackTrace();
            }

            return ResponseEntity.ok(userInfo);
        }

        //检查是否登录，如果没有登录就更应该返回401，表示未登录授权
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();


    }


}
